//
//  WBHomeViewController.swift
//  DXWeibo
//
//  Created by dx on 2017/1/3.
//  Copyright © 2017年 dx. All rights reserved.
//

import UIKit

/// 定义全局常量，尽量使用 private 修饰
/// 原创微博可重用 cell id
private let originalCellId = "originalCellId"
/// 被转发微博的可重用 cell id
private let retweetedCellId = "retweetedCellId"

class WBHomeViewController: WBBaseViewController {

    fileprivate lazy var listViewModel = WBStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 注册通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(selectedPhoto),
            name: NSNotification.Name(rawValue: WBStatusCellBrowserPhotoNotification),
            object: nil)
    }
    
    deinit {
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - 监听方法
    @objc private func selectedPhoto(n: Notification) {
        
        guard let selectedIndex = n.userInfo?[WBStatusCellBrowserPhotoSelectedIndexKey] as? Int,
            let urls = n.userInfo?[WBStatusCellBrowserPhotoURLsKey] as? [String] else {
                return
        }
        
        let browser = PhotoBrowserController(selectedIndex: selectedIndex, urls: urls)
        
        // 指定 modal 展现为自定义样式
        browser.modalPresentationStyle = .custom
        
        present(browser, animated: true, completion: nil)
    }
    
    // 浏览照片通知的监听方法
//    @objc private func browserPhoto(n: Notification) {
//        
//        // 1. 从通知的 userInfo 提取参数
//        guard let selectedIndex = n.userInfo?[WBStatusCellBrowserPhotoSelectedIndexKey] as? Int,
//            let urls = n.userInfo?[WBStatusCellBrowserPhotoURLsKey] as? [String],
//            let imageViewList = n.userInfo?[WBStatusCellBrowserPhotoImageViewsKey] as? [UIImageView] else {
//                return
//        }
//        
//        // 2. 展现照片浏览控制器
//        let vc = HMPhotoBrowserController.photoBrowser(
//            withSelectedIndex: selectedIndex,
//            urls: urls,
//            parentImageViews: imageViewList)
//        present(vc, animated: true, completion: nil)
//    }
    
    /// 加载数据
    override func loadData() {
        
        print("准备刷新")
        refreshControl?.beginRefreshing()
        
        // 模拟延时加载数据
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
            
            self.listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldRefresh) in
                print("加载数据结束")
                // 结束刷新控件
                self.refreshControl?.endRefreshing()
                
                // 恢复上拉刷新标记
                self.isPullup = false
                
                // 刷新表格
                if shouldRefresh {
                    self.tableView?.reloadData()
                }
            }
        }
        
    }
    
    /// 显示好友
    @objc fileprivate func showFriends() {
        
        let vc = WBTestViewController()
        
        // push 的动作是 nav 做的
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - 表格数据源方法
extension WBHomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 取出视图模型，判断可重用 cell
        let vm = listViewModel.statusList[indexPath.row]
        
        let cellId = (vm.status.retweeted_status != nil) ? retweetedCellId : originalCellId
        
        // 取 cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! WBStatusCell
        
        // 设置 cell
        cell.viewModel = vm
        
        // --- 设置代理 --- 
        // 如果用 block 需要在数据源方法中，给每一个 cell 设置 block
        // cell.completionBlock = { // ... }
        // 设置代理只是传递了一个指针地址
        cell.delegate = self

        // 返回 cell
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        // 1. 根据 indexPath 获取视图模型
        let vm = listViewModel.statusList[indexPath.row]
        
        // 2. 返回计算好的行高
        return vm.rowHeight
    }
}

// MARK: - WBStatusCellDelegate
extension WBHomeViewController: WBStatusCellDelegate {
    
    func statusCellDidSelectedURLString(cell: WBStatusCell, urlString: String) {
        
        let vc = WBWebViewController()
        
        vc.urlString = urlString
        
        navigationController?.pushViewController(vc, animated: true)
    }
}


// MARK: - 设置界面
extension WBHomeViewController {
    
    /// 重写父类方法
    override func setupTableView() {
        super.setupTableView()

        // 设置导航栏按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
        // 注册原型 cell        
        tableView?.register(UINib(nibName: "WBStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        tableView?.register(UINib(nibName: "WBStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellId)
        
        // 设置行高
        // 取消自动行高
        // tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 300
        
        // 取消分隔线
        tableView?.separatorStyle = .none
        
        setupNavTitle()
        
        clickTitleButton(btn: navItem.titleView as! UIButton)
        clickTitleButton(btn: navItem.titleView as! UIButton)
        
    }
    
    /// 设置导航栏标题
    private func setupNavTitle() {
        
        let title = WBNetworkManager.shared.userAccount.screen_name
        
        let button = WBTitleButton(title: title)
        
        button.addTarget(self, action: #selector(clickTitleButton(btn:)), for: .touchUpInside)
        
        navItem.titleView = button
        
    }
    
    @objc fileprivate func clickTitleButton(btn: UIButton) {
        
        // 设置选中状态
        btn.isSelected = !btn.isSelected
    }
    
}







